//
//  HRTopicListViewController.m
//  Hear
//
//  Created by mac on 2017/11/27.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRTopicListViewController.h"
#import "HRTopicListCell.h"
#import "MJRefresh.h"
#import "HRFunChatViewModel.h"
#import "HRPostSoundViewModel.h"
#import "HRTopicListLayout.h"
#import "HRRecordAudioViewController.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface HRTopicListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *contentArray;
@property (nonatomic, assign)NSInteger pIndex;
@property(nonatomic, strong)HRFunChatViewModel *viewModel;
@property(nonatomic, strong)HRFunChatModel *lastFunModel;
@property (nonatomic, strong)HRPostSoundViewModel *saveSoundModel;

@end

@implementation HRTopicListViewController
#pragma mark - Get and Set
- (HRPostSoundViewModel *)saveSoundModel{
    if (_saveSoundModel == nil) {
        _saveSoundModel = [[HRPostSoundViewModel alloc] init];
    }
    return _saveSoundModel;
}

- (HRFunChatViewModel *)viewModel{
    if (_viewModel == nil) {
        _viewModel = [[HRFunChatViewModel alloc] init];
    }
    return _viewModel;
}

- (NSMutableArray *)contentArray{
    if (_contentArray == nil) {
        _contentArray = [[NSMutableArray alloc] init];
    }
    return _contentArray;
}
- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [UITableView new];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.frame = self.view.bounds;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedRowHeight = 0;
    }
    [self getFunChatContent];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.contentArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HRTopicListLayout *model = self.contentArray[indexPath.row];
    return model.cellHeight;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HRTopicListCell *cell = [HRTopicListCell cellWithTableView:tableView];
    HRTopicListLayout *model = self.contentArray[indexPath.row];
    cell.layout = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    WeakSelf
    cell.playFunChatMedioBlock = ^(HRFunChatModel *funChatModel) {
        if (funChatModel || self.lastFunModel){
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![funChatModel.LocalId isEqualToString:weakSelf.lastFunModel.LocalId]){
                    weakSelf.lastFunModel.isPlaying = NO;
                }
                [weakSelf.tableView reloadData];
                if (weakSelf.contentArray.count < 20){
                    weakSelf.tableView.mj_footer.hidden = YES;
                }
                self.lastFunModel = funChatModel;
            });
        }
    };
    
    cell.sendBlock = ^{
        [weakSelf saveUserTopic:model.chatModel];
    };
    cell.delelteCurrentTopicBlock = ^{
        [weakSelf deleteUserTopic:model.chatModel andCurrentIndex:indexPath.row];
    };
    return cell;
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"空白"];
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state{
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    text = @"啊哦，话题空空如也，快去发布一个吧~";
    font = CustomUIFont(16);
    textColor = FirstTextColor;
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
#pragma mark - DZNEmptyDataSetDelegate Methods
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    HRRecordAudioViewController *VC = [HRRecordAudioViewController new];
    VC.title = @"创建话题";
    VC.isFromTopic = YES;
    VC.soundRemendText = @"请输入你要创建的话题内容";
    [self.navigationController pushViewController:VC animated:YES];
}





-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)deleteUserTopic:(HRFunChatModel *)model andCurrentIndex:(NSUInteger)index{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserTopicLocalId"] = model.LocalId;
    paramDict[@"UserLocalId"] = USERID;
    WeakSelf
    [self.saveSoundModel deleteUserTopic:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            [MBProgressHUD showMessage:@"已删除" finishBlock:nil];
            
            [weakSelf.contentArray removeObjectAtIndex:index];
            [weakSelf.tableView deleteRow:index inSection:0 withRowAnimation:UITableViewRowAnimationRight];
            [weakSelf.tableView reloadData];
            if (weakSelf.contentArray.count < 20){
                weakSelf.tableView.mj_footer.hidden = YES;
            }
            
        }
    }];
}

- (void)saveUserTopic:(HRFunChatModel *)model{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"LocalId"] = model.LocalId;
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"TopicTitle"] = model.TopicTitle;
    paramDict[@"SoundUrl"] = model.SoundUrl;
    paramDict[@"SoundLength"] = model.SoundLength;
    paramDict[@"TopicDes"] = @"";
    paramDict[@"IsUse"] = @"1";
    paramDict[@"CreateTime"] = [self getCurrentTime];
    
    WeakSelf
    [self.saveSoundModel setUserTopicUsable:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            [MBProgressHUD showMessage:@"已重新发布" finishBlock:nil];
            [weakSelf getFunChatContent];
        }
    }];
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}

- (void)getFunChatContent{
    self.pIndex = 0;
    
    [self getFunChatData:YES];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getFunChatData:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getFunChatData:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)getFunChatData:(BOOL)isHead{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"PageSize"] = @"20";
    paramDict[@"PageIndex"] = [NSString stringWithFormat:@"%d",self.pIndex];
    paramDict[@"CurrentUserLocalId"] = USERID;
    WeakSelf
    [self.viewModel getMyUserTopicList:paramDict contentArr:^(NSMutableArray *contentArr) {
        if (contentArr){
            if (isHead){
                [weakSelf.contentArray removeAllObjects];
            }
            [weakSelf.contentArray addObjectsFromArray:contentArr];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                if (contentArr.count < 20){
                    weakSelf.tableView.mj_footer.hidden = YES;
                }
                if (!weakSelf.contentArray.count){
                    [MBProgressHUD showMessage:@"暂无数据" finishBlock:nil];
                }
            });
            
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
